# -*- coding: utf-8 -*-
########################################################################
#   Pax-Selector. Copyright 2010, Hector Sanjuán.                      #
#                                                                      #
#   Pax-selector is free software: you can redistribute it and/or      #
#   modify it under the terms of the GNU General Public License as     #
#   published by the Free Software Foundation, either version 3 of     #
#   the License, or any later version.                                 #
#                                                                      #
#   Pax-selector is distributed in the hope that it will be useful,    #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of     #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      #
#   GNU General Public License for more details.                       #
#                                                                      #
#   You should have received a copy of the GNU General Public License. #
#   If not, see <http://www.gnu.org/licenses/>.                        #
#                                                                      #
########################################################################

require 'userInfo'

Warden::Manager.serialize_into_session{|user| user.id }
Warden::Manager.serialize_from_session{|key| UserInfo.get_from_id key }

Warden::Manager.before_failure do |env,opts|
  # Sinatra is very sensitive to the request method
  # since authentication could fail on any type of method, we need
  # to set it for the failure app so it is routed to the correct block
  env['REQUEST_METHOD'] = "POST"
end

Warden::Strategies.add(:password) do
  def valid?
    params["name"] || params["password"]
  end

  def authenticate!
    user = UserInfo.authenticate(params["name"],params["password"])
    user ? success!(user) : fail!("Could not log in")
  end
end
